<template>
  <container :title="(form.coupon_id ? '编辑':'添加') + '优惠券'">
    <div class="main-card">
      <el-tabs v-model="tabName">
        <el-tab-pane name="base" label="基础信息">
          <div style="height: 10px"></div>
          <tbc-dynamic-form :form="dynamicForm1" class="compact">
            <template #discount="scope">
              <span style="color: #606266">消费满</span>
              <el-input-number style="width:220px;margin:0 10px"
                               :disabled="scope.item.disabled"
                               v-model="form.minimum" controls-position="right"/>
              <span style="color: #606266">减</span>
              <el-input-number style="width:160px;margin:0 10px"
                               :disabled="scope.item.disabled"
                               v-model="scope.item.value" controls-position="right"/>
            </template>
          </tbc-dynamic-form>
        </el-tab-pane>

        <el-tab-pane name="release" label="发放设置">
          <div style="height: 10px"></div>
          <tbc-dynamic-form :form="dynamicForm2" class="compact">
          </tbc-dynamic-form>
        </el-tab-pane>

        <el-tab-pane name="effective" label="使用限制">
          <div style="height: 10px"></div>
          <tbc-dynamic-form :form="dynamicForm3" @change="onFormChange" class="compact">
            <template #effective_type="scope">
              <el-radio-group v-model="scope.item.value" :disabled="scope.item.disabled">
                <el-radio :label="1">
                  <el-date-picker type="datetimerange" :disabled="scope.item.disabled || scope.item.value !== 1"
                                  v-model="timeSection"></el-date-picker>
                </el-radio>

                <el-radio :label="2">
                  领券当日起
                  <el-input-number style="width:120px;margin:0 10px"
                                   :disabled="scope.item.value !==2  || scope.item.disabled"
                                   v-model="form.effective_days" controls-position="right"/>
                  <span>天内有效</span>
                </el-radio>
              </el-radio-group>
            </template>
          </tbc-dynamic-form>
          <el-button type="text" @click="$refs.goods.show()" v-if="form.use_scope > 1">
            选择商品
          </el-button>
          <div style="padding-right: 20px"
               v-show="form.use_scope > 1 && couponGoodsList.length">
            <tbc-dynamic-table
                :data="couponGoodsList"
                max-height="450"
                :cols="[
      {label: '商品信息', prop: 'base', width: 400},
      {label: '销售价', prop: 'shop_price', type: '', align: 'center'},
      {label: '销售状态', prop: 'sale_status', type: '', align: 'center'},
      {label: '操作', width: 60, type: 'action', prop: 'action',  button: [
          {label: '删除', type: 'text', click: removeCouponGoods}
      ]}]">
              <template #base="scope">
                <div style="float:left;width:70px;height:70px;">
                  <el-image :src="scope.row.goods_image"></el-image>
                </div>
                <div style="padding:0 50px 0 90px;">
                  <p>{{ scope.row.goods_id }}</p>
                  <p class="">
                    <span class="">{{ scope.row.goods_name }}</span>
                  </p>
                </div>
              </template>
              <template #sale_status="scope">

                <el-tag size="mini" effect="dark" type="success" v-if="scope.row.sale_status === 1">销售</el-tag>
                <el-tag size="mini" effect="dark" type="primary" v-if="scope.row.sale_status === 2">仓库</el-tag>
              </template>
            </tbc-dynamic-table>
          </div>
        </el-tab-pane>
        <el-tab-pane name="desc" label="使用说明">
          <div style="height: 10px"></div>
          <tbc-dynamic-form :form="dynamicForm4" class="compact"/>
        </el-tab-pane>
      </el-tabs>
      <div style="margin-top: 20px">
        <el-button type="primary" @click="formSubmit">保存</el-button>
        <el-button onclick="history.back()">返回</el-button>
      </div>
    </div>
  </container>
  <goods-selector ref="goods" @choice="onGoodsSelected"/>
</template>
<script lang="ts">
import {
  defineComponent, reactive, onMounted, toRefs,
  defineAsyncComponent
} from 'vue'
import useCoupon from './api/coupon'
import useCouponGoods from './api/couponGoods'
import {useRoute} from "vue-router";

export default defineComponent({

  name: 'coupon-form',
  components: {
    GoodsSelector: defineAsyncComponent(
        () => import('@/views/mall/goods/GoodsSelector.vue'))
  },
  setup() {
    const coupon = useCoupon()
    const couponGoods = useCouponGoods()
    const route = useRoute()
    const state = reactive({
      loading: false,
      tabName: 'base',
      dynamicForm1: [
        {label: '优惠券名称', value: '', field: 'coupon_name', type: 'input'},
        {
          label: '发行总量',
          value: '',
          field: 'coupon_total',
          type: 'input-number',
        },
        {
          label: '满减设置',
          value: '',
          field: 'discount',
          type: 'input-number'
        },
        {
          label: '状态', value: 1, field: 'status', type: 'radio',
          options: [
            {value: 1, label: '使用'},
            {value: 2, label: '禁用'}
          ]
        }
      ],
      dynamicForm2: [
        {
          label: '领取方式', value: 1, field: 'distribution_method', type: 'select',
          options: [
            {value: 1, label: '默认领取'},
            {value: 2, label: '注册赠送'},
          ]
        },
        {
          label: '每人限领',
          value: '',
          field: 'quota',
          type: 'input-number'
        },
        {
          label: '可领取时间',
          value: [],
          field: 'release_time',
          type: 'datetimerange',
          style: 'width:400px'
        }
      ],
      dynamicForm3: [
        {
          label: '使用有效期', value: 1, field: 'effective_type', type: 'radio',
          options: [
            {value: 1, label: '指定日期'},
            {value: 2, label: '领券当日'},
          ]
        },
        {
          label: '使用范围', value: 1, field: 'use_scope', type: 'radio',
          options: [
            {value: 1, label: '全部'},
            {value: 2, label: '指定商品可用'},
            {value: 3, label: '指定商品不可用'},
          ]
        }
      ],
      dynamicForm4: [
        {
          label: '使用说明', value: '', field: 'coupon_desc', type: 'textarea', rows: 8
        }
      ],
      form: {
        coupon_id: route.query.id || '',
        effective_days: '',
        use_scope: 1,
        distribution: 0,
        coupon_desc: '',
        minimum: '',
        effective_start_time: '',
        effective_end_time: '',
      },
      timeSection: [new Date(), ''],
      couponGoodsList: []
    })

    const onFormChange = (index: number) => {
      state.dynamicForm3.forEach(item => state.form[item.field] = item.value)
    }

    const formSubmit = async () => {
      const form = JSON.parse(JSON.stringify(state.form))
      state.dynamicForm1.forEach(item => form[item.field] = item.value)
      state.dynamicForm2.forEach(item => form[item.field] = item.value)
      state.dynamicForm3.forEach(item => form[item.field] = item.value)
      state.dynamicForm4.forEach(item => form[item.field] = item.value)
      form.effective_start_time = state.timeSection[0] || ''
      form.effective_end_time = state.timeSection[1] || ''
      form.release_start_time = form.release_time[0] || ''
      form.release_end_time = form.release_time[1] || ''
      const goodsIdList = []
      state.couponGoodsList.forEach(item => goodsIdList.push(item.goods_id))
      form.goods = goodsIdList.join(',')
      const res = await coupon.update(form)
      // if (res.data.code === 0)
    }

    const getCouponInfo = async () => {
      if (!state.form.coupon_id) return
      getCouponGoods().then()
      const res = await coupon.getInfo(state.form.coupon_id as string)
      if (res.data.code !== 0) return
      const data: any = res.data.data
      state.dynamicForm1.forEach((item: Record<string, any>) => {
        item.value = data[item.field]
      })
      state.dynamicForm2.forEach((item: Record<string, any>) => {
        item.value = data[item.field]
        if (item.field === 'release_time') {
          item.value = [data.release_start_time, data.release_end_time]
        } else {
          item.value = data[item.field]
        }
      })
      state.dynamicForm3.forEach((item: Record<string, any>) => {
        item.value = data[item.field]
      })
      state.dynamicForm4.forEach((item: Record<string, any>) => {
        item.value = data[item.field]
      })
      state.timeSection = [data.effective_start_time, data.effective_end_time]
      for (let i in state.form) state.form[i] = data[i]
    }

    const getCouponGoods = async () => {
      (couponGoods.couponId.value as any) = state.form.coupon_id
      const res = await couponGoods.loadDataList()
      if (res.data.code !== 0) return
      state.couponGoodsList = res.data.data.list
    }

    const onGoodsSelected = (data) => {
      const index = state.couponGoodsList.findIndex(item =>
          item.goods_id == data.goods_id)
      if (index > -1) return
      state.couponGoodsList.push(data)
    }

    onMounted(() => {
      getCouponInfo()
    })

    return {
      ...toRefs(state),
      onFormChange,
      formSubmit,
      onGoodsSelected
    }
  }
})
</script>